package handler

import (
	"encoding/json"
	"sep19-homework/cache"
	"sep19-homework/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var new []model.New

	redis_key := "new_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&new)

		jsonData, _ := json.Marshal(new)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &new)
	}

	var total int64
	model.DB.Model(&new).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"new":   new,
		"total": total,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var new []model.New

	redis_key := "new_select_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&new)

		jsonData, _ := json.Marshal(new)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &new)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"new":  new,
	})
	return
}
